package com.keenote.http;

import lombok.extern.slf4j.Slf4j;
import org.springframework.http.HttpHeaders;

import java.io.IOException;
import java.io.InputStream;
import java.net.URL;
import java.util.Properties;

/**
 * description
 *
 * @author mic.zhou
 * @date 2022/8/23 10:17
 */
@Slf4j
public class CookieManager {
    /**
     * Cookie 配置
     */
    private static final Properties cookies = new Properties();

    static {
        try (InputStream is = CookieManager.class.getClassLoader().getResourceAsStream("cookies.properties")) {
            cookies.load(is);
        } catch (IOException e) {
            throw new RuntimeException(e);
        }
    }

    /**
     * 获取某个域名下的Cookie至
     * @param url url
     * @return 结果
     */
    public static String getHostCookie(String url) {
        try {
            return cookies.getProperty(new URL(url).getHost());
        } catch (Exception e) {
            log.error("Cookie获取失败！", e);
        }
        return null;
    }

    /**
     * 获取含有Cookie的Header
     *
     * @param url url
     * @return 结果
     */
    public static HttpHeaders getCookieHeader(String url) {
        HttpHeaders httpHeaders = new HttpHeaders();
        httpHeaders.add(HttpHeaders.COOKIE, getHostCookie(url));
        return httpHeaders;
    }
}
